<?php
/**
 *	后台验证码生成控制器
 *	@author		
 *	@version	1.0
 *	@package	controllers
 *
 */

class CaptchaController extends Controller
{
	/**
	 * Class constructor
	 */
	protected function beforeAction($action)
	{
		parent::beforeAction($action);
		
		return true;
	}
	
	public function actionIndex()
	{
		$session = new CHttpSession();
		$session->open();
		
		//RANDOM CHR
		$rndstring = '';
		for($i = 0; $i < 4; $i ++)
			$rndstring .= chr ( mt_rand ( 65, 90 ) );
			//create picture
		if (function_exists ( "imagecreate" )) {
			// 5 seconds refersh didn't change session for firefox
			$ntime = time ();
			$ckstr_last = $session [ 'ckstr_last' ] ? $session [ 'ckstr_last' ] : '';
			if ($session [ 'ckstr_last' ] === FALSE || $session [ 'ckstr' ] === FALSE || ($ntime - $session [ 'ckstr_last' ] >= 0)) {
				$session ['ckstr'] = strtolower ( $rndstring );
				$session ['ckstr_last'] = strtolower ( $ntime );
			}
			$rndstring = $session [ 'ckstr' ];
			$rndcodelen = strlen ( $rndstring );
			//create picture set bgcolor
			$im = imagecreate ( 50, 20 );
			ImageColorAllocate ( $im, 255, 255, 255 );
			
			//backround line
			$lineColor1 = ImageColorAllocate ( $im, 240, 220, 180 );
			$lineColor2 = ImageColorAllocate ( $im, 250, 250, 170 );
			for($j = 3; $j <= 16; $j = $j + 3) {
				imageline ( $im, 2, $j, 48, $j, $lineColor1 );
			}
			for($j = 2; $j < 52; $j = $j + (mt_rand ( 3, 6 ))) {
				imageline ( $im, $j, 2, $j - 6, 18, $lineColor2 );
			}
			
			//draw border
			//$bordercolor = ImageColorAllocate ( $im, 0x99, 0x99, 0x99 );
			//imagerectangle ( $im, 0, 0, 49, 19, $bordercolor );
			
			//outputer fonts
			$fontColor = ImageColorAllocate ( $im, 48, 61, 50 );
			for($i = 0; $i < $rndcodelen; $i ++) {
				$bc = mt_rand ( 0, 1 );
				$rndstring [$i] = strtoupper ( $rndstring [$i] );
				imagestring ( $im, 5, $i * 10 + 6, mt_rand ( 2, 4 ), $rndstring [$i], $fontColor );
			}
			//other 
			for($i = 0; $i < 300; $i ++) {
				$randcolor = ImageColorallocate ( $im, rand ( 0, 255 ), rand ( 0, 255 ), rand ( 0, 255 ) );
				imagesetpixel ( $im, rand () % 90, rand () % 30, $randcolor );
			}
			header ( "Pragma:no-cache\r\n" );
			header ( "Cache-Control:no-cache\r\n" );
			header ( "Expires:0\r\n" );
			
			//print pictures(gif -> jpg ->png)
			if (function_exists ( "imagejpeg" )) {
				header ( "content-type:image/jpeg\r\n" );
				imagejpeg ( $im );
			} else {
				header ( "content-type:image/png\r\n" );
				imagepng ( $im );
			}
			ImageDestroy ( $im );
			exit ();
		} else {
			//if server doesn't support GD echo ABCD
			$session ['ckstr'] = 'abcd';
			$session ['ckstr_last'] = '';
			header ( "content-type:image/jpeg\r\n" );
			header ( "Pragma:no-cache\r\n" );
			header ( "Cache-Control:no-cache\r\n" );
			header ( "Expires:0\r\n" );
			$fp = fopen ( Yii::app()->params['basePath']."imgs/vdcode.jpg", "r" );
			echo fread ( $fp, filesize ( Yii::app()->params['basePath']."imgs/vdcode.jpg" ) );
			fclose ( $fp );
			exit ();
		}
	}

}

?>